<template>
  <div class="home">
    <h3>wangEditor with vue</h3>
    <div id="demo1"></div>
    <button type="button" class="btn" @click="getEditorData">获取当前内容</button>
    <!-- <h3>内容预览</h3>
    <textarea name="" id="" cols="170" rows="20" readonly style="width:100%" v-model="editorData"></textarea>-->
  </div>
</template>

<script>
// 引入 wangEditor
import wangEditor from "wangeditor";
import { uploadOSS } from "@/utils/oss.js";
export default {
  data() {
    return {
      editor: null,
      editorData: ""
    };
  },
  mounted() {
    const editor = new wangEditor(`#demo1`);
    // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = newHtml => {
      this.editorData = newHtml;
      this.$emit("editorContent", newHtml);
    };
    //开启上传图片 关闭填写地址栏模式
    editor.config.uploadImgServer = "/api/upload-img";
    editor.config.excludeMenus = [
      //定义不需要显示的菜单
      "video"
    ];
    //关闭全屏显示
    editor.config.showFullScreen = false;
    // 创建编辑器
    editor.create();
    this.editor = editor;
    //测试
    editor.txt.html("<p>有内容时则展示</p>");
    editor.config.customUploadImg = (resultFiles, insertImgFn) => {
      //拿到上传的文件
      console.log(resultFiles);
      //将上传的文件转成url传入insertImgFn方法 例如下面的阿里云OSS
      insertImgFn(
        "https://img2.baidu.com/it/u=462228203,2921554562&fm=26&fmt=auto"
      );

      //这部分是先把图片上传到阿里云拿到fileUrl，在调用insertImgFn
      // let alist = [];
      // for (let index = 0; index < resultFiles.length; index++) {
      //   uploadOSS(resultFiles[index], resultFiles[index].name, "ZKX/").then(
      //     fileUrl => {
      //       alist.push({ idx: index, fileUrl: fileUrl });
      //       if (alist.length == resultFiles.length) {
      //         const newalist = alist.sort(compare("idx"));
      //         newalist.forEach(o => {
      //           insertImgFn(o.fileUrl);
      //         });
      //       }
      //     }
      //   );
      // }
    };
  },
  methods: {
    getEditorData() {
      // 通过代码获取编辑器内容
      let data = this.editor.txt.html();
      alert(data);
    }
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy();
    this.editor = null;
  }
};
</script>

<style lang="scss" scoped>
.home {
  width: 1200px;
  margin: auto;
  position: relative;
  .btn {
    position: absolute;
    right: 0;
    top: 0;
    padding: 5px 10px;
    cursor: pointer;
  }
  h3 {
    margin: 30px 0 15px;
  }
}
</style>